from math import pi, sin, log, floor

   
def getTileFromCoords(lat, lng, zoom):
    DTOR = pi / 180.
    RTOD = 180. / pi
    
    TILE_SIZE = 256
    sin_phi = sin(float(lat) * DTOR)
    # Use Mercator to calculate x and normalize this to -1 <= x <= +1 by division by 180.
    # The center of the map is lambda_0 = 0, hence x = lat. 
    norm_x = lng / 180.
    # Use Mercator to calculate y and normalize this to -1 <= y <= +1 by division by PI. 
    # According to Mercator y is defined in the range of -PI <= y <= PI only 
    norm_y = (0.5 * log((1 + sin_phi) / (1 - sin_phi))) / pi
    # Apply the normalized point coordinations to any application (here the coordinates of 
    # a 256*256 image holding that point in a thought grid with origin 0,0 top/left)
    col = int(pow(2, zoom) * ((norm_x + 1) / 2))
    row = int(pow(2, zoom) * ((1 - norm_y) / 2))
    return (col, row, zoom)

def getTileBoundsFromCoords(swLat, swLng, neLat, neLng, zoom):
    swTiles = getTileFromCoords(swLat, swLng, zoom)
    neTiles = getTileFromCoords(neLat, neLng, zoom)
    return (swTiles, neTiles)
        